#include "util.hpp"
#include <iostream>
#include <functional>
#include <vector>

using func_t = std::function<void()>;

inline void INIT(std::vector<func_t> &cbs)
{
    cbs.push_back(printLog);
    cbs.push_back(downLoad);
    cbs.push_back(executeSql);
}

inline void execOther(std::vector<func_t> &cbs)
{
    for (const auto &cb : cbs)
        cb();
    sleep(1);
}

// 以轮询方式从0文件描述符接收数据为例
int main()
{
    std::vector<func_t> cbs;
    INIT(cbs);

    SetNoBlock(0);
    while (true)
    {
        char buffer[64];
        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            if (buffer[n - 1] == '\n')
                buffer[n - 1] = 0;
            else
                buffer[n] = 0;

            std::cout << "echo:" << buffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "read end" << std::endl;
            break;
        }
        else
        {
            std::cout << "return result:" << n << " errno:" << errno << std::endl;

            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "无数据可读,执行我的方法" << strerror(errno) << std::endl;
                execOther(cbs);
            }
            else if (errno == EINTR)
            {
                std::cout << "read被中断,需要重新读取数据" << strerror(errno) << std::endl;
                continue;
            }
            else
            {
                std::cout << "read调用出错:" << strerror(errno) << std::endl;
                return errno;
            }
        }
    }

    return 0;
}